#include "aerial\Game\Helper\AirContactListener.h"
#include "aerial\Game\GameObject\FlyObject\FlyObject.h"
#include "aerial\Game\GameObject\Equipment\Weapon.h"

void AirContactListener::BeginContact(b2Contact* contact)
{
	if (!contact->GetFixtureA()->GetBody()->GetUserData()) return;
	if (!contact->GetFixtureB()->GetBody()->GetUserData()) return;

	GameObject* obj_a = (GameObject*)contact->GetFixtureA()->GetBody()->GetUserData();
	GameObject* obj_b = (GameObject*)contact->GetFixtureB()->GetBody()->GetUserData();
	if (!obj_a->toDestroy && !obj_b->toDestroy)
	{
		ContactSet.insert(ContactObject(obj_a, obj_b));
	}
}

void AirContactListener::PreSolve(b2Contact* contact, const b2Manifold* oldManifold)
{
	if (!contact->GetFixtureA()->GetBody()->GetUserData()) return;
	if (!contact->GetFixtureB()->GetBody()->GetUserData()) return;

	GameObject* obj_a = (GameObject*)contact->GetFixtureA()->GetBody()->GetUserData();
	GameObject* obj_b = (GameObject*)contact->GetFixtureB()->GetBody()->GetUserData();
	if (obj_a->toDestroy || obj_b->toDestroy)
	{
		contact->SetEnabled(false);
	}
}

void AirContactListener::EndContact(b2Contact* contact)
{
	if (!contact->GetFixtureA()->GetBody()->GetUserData()) return;
	if (!contact->GetFixtureB()->GetBody()->GetUserData()) return;

	GameObject* obj_a = (GameObject*)contact->GetFixtureA()->GetBody()->GetUserData();
	GameObject* obj_b = (GameObject*)contact->GetFixtureB()->GetBody()->GetUserData();
	ContactSet.erase(ContactObject(obj_a, obj_b));
}

void AirContactListener::process(float dt)
{
	set<ContactObject>::iterator it = ContactSet.begin(), next;
	while (it != ContactSet.end())
	{
		if (it->a->GetObjectType() == TYPE_FLY && it->b->GetObjectType() == TYPE_FLY)
		{
			FlyObject* a = (FlyObject*)it->a;
			FlyObject* b = (FlyObject*)it->b;
			b->TakeEffect(a);
			a->TakeEffect(b);
		}
		else if (it->a->GetObjectType() == TYPE_FLY)
		{
			FlyObject* a = (FlyObject*)it->a;
			a->TakeEffect((Weapon*)it->b);
		}
		else if (it->b->GetObjectType() == TYPE_FLY)
		{
			FlyObject* b = (FlyObject*)it->b;
			b->TakeEffect((Weapon*)it->a);
		}
		it++;
	}
}